import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

Vue.use(VueRouter)

// // 解决重复路由报错

//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}
// // 解决重复路由报错
const routes = [
  // 重定向
  {path: '/',redirect:'/allmessage'},
  // 登录
  {path: '/login',component: () => import('@/views/login.vue')},
  {
    path: '/index',
    component: () => import('@/views/index.vue'),
    children:[
      {path:"/business",component: () => import("@/components/salesystem/business.vue")},
      {path:"/allmessage",component: () => import("@/components/allmessage/index.vue")},
      {path:"/worker",component: () => import("@/components/worker/index.vue")},
      {path:"/customer",component: () => import("@/components/customer/index.vue")},
      {path:"/roomsystem",component: () => import("@/components/roomsystem/index.vue")},
    ]

  },
  {path:"/brand/message",component: () => import("@/components/brand/message/index.vue")},
  {path:"/invite/business",component: () => import("@/components/brand/Invite-business/index.vue")},
  {path:"/invite/business/detail",component: () => import("@/components/brand/Invite-business/detail.vue")},
  {path:"/join/business",component: () => import("@/components/brand/join-business/index.vue")},
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


// vue路由跳转时定位到页面顶部的方法
router.afterEach((to, from, next) => {
  // console.log(to,from)
  window.scrollTo(0, 0)
})


// 路由守卫
// 路由守卫核心代码
// (  一定要加  next()  否则页面不出现   )
router.beforeEach((to,from,next) => {
  console.log(to)
  var token=window.localStorage.getItem("systemToken")
  if (to.path == '/login' && !token){
    next()
  }
  // 没令牌，则返回登录页面
  else if(!token){
    next('/login')
  }
  // 令牌存在，则禁止返回登录页面
  else if(token&&to.path == '/login'){
    next('/index')
  }
  else{
    next()
  }
  
})


export default router
